package com.kevin.permission.service;


import com.google.common.base.Preconditions;
import com.kevin.permission.common.RequestHolder;
import com.kevin.permission.dao.SysAclMapper;
import com.kevin.permission.dao.SysAclModuleMapper;
import com.kevin.permission.exception.ParamsException;
import com.kevin.permission.model.SysAclModule;
import com.kevin.permission.param.AclModuleParam;
import com.kevin.permission.util.BeanValidator;
import com.kevin.permission.util.IpUtil;
import com.kevin.permission.util.LevelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysAclModuleService {

    @Autowired
    private SysAclModuleMapper sysAclModuleMapper;

    @Autowired
    private SysAclMapper sysAclMapper;
    
    public void save(AclModuleParam param) {
        BeanValidator.check(param);
        if (checkExist(param.getParentId(),param.getName(),param.getId())){
            throw new ParamsException("同一层级下存在相同的权限模块");
        }

        SysAclModule aclModule=SysAclModule.builder().name(param.getName()).parentId(param.getParentId()).seq(param.getSeq())
                .status(param.getStatus()).remark(param.getRemark()).build();
        aclModule.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()),param.getParentId()));
        aclModule.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        aclModule.setOperator(RequestHolder.getCurrentUser().getUsername());
        aclModule.setOperatorTime(new Date());
        sysAclModuleMapper.insertSelective(aclModule);
    }

    public void update(AclModuleParam param) {
        BeanValidator.check(param);
        if (checkExist(param.getParentId(),param.getName(),param.getId())){
            throw new ParamsException("同一层级下存在相同的权限模块");
        }
        SysAclModule before=sysAclModuleMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新模块不存在");

        SysAclModule after=SysAclModule.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId()).seq(param.getSeq())
                .status(param.getStatus()).remark(param.getRemark()).build();
        after.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()),param.getParentId()));
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperatorTime(new Date());

        updateWithChild(before,after);
    }

    private void updateWithChild(SysAclModule before, SysAclModule after) {
        String newLevelPrefix=after.getLevel();
        String oldLevelPrefix=before.getLevel();
        if (!newLevelPrefix.equals(oldLevelPrefix)){
            List<SysAclModule> aclModuleList=sysAclModuleMapper.getChildAclModuleListByLevel(before.getLevel());
            if (CollectionUtils.isNotEmpty(aclModuleList)){
                for (SysAclModule aclModule: aclModuleList){
                    String level=aclModule.getLevel();
                    if (level.indexOf(oldLevelPrefix)==0){
                        level=newLevelPrefix+level.substring(oldLevelPrefix.length());
                        aclModule.setLevel(level);
                    }
                }
                sysAclModuleMapper.batchUpdateLevel(aclModuleList);
            }
        }
        sysAclModuleMapper.updateByPrimaryKeySelective(after);
    }

    public void delete(int id) {
        SysAclModule aclModule=sysAclModuleMapper.selectByPrimaryKey(id);
        Preconditions.checkNotNull(aclModule,"待删除的模块权限不存在，无法删除");
        if (sysAclModuleMapper.countByParentId(aclModule.getId())>0){
            throw new ParamsException("当前模块下面有子模块，无法删除");
        }
        //TODO FIXME
//        if (sysAclMapper.countByAclModuleId(aclModule.getId())>0){
//            throw new ParamsException("当前模块下有权限，无法删除");
//        }
        sysAclModuleMapper.deleteByPrimaryKey(id);
    }


    private boolean checkExist(Integer parentId, String aclModuelName, Integer aclModuleId) {
        return sysAclModuleMapper.countByNameAndParentId(parentId,aclModuelName,aclModuleId) >0;
    }


    private String getLevel(Integer parentId) {
        SysAclModule aclModule=sysAclModuleMapper.selectByPrimaryKey(parentId);
        if (aclModule==null){
            return null;
        }
        return aclModule.getLevel();
    }

}
